import functools
import time


def get_func_params(func, *args, **kwargs):
    dict_param = {}
    if len(args) > 0:
        var_names = func.__code__.co_varnames
        if len(args) == len(var_names):
            for i in range(len(var_names)):
                dict_param.update({var_names[i]: args[i]})

    if len(kwargs) > 0:
        dict_param.update(kwargs.items())

    return dict_param


def with_method_logging(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        t_begin = time.time()
        print('%s method start at %0.4f' % (func.__name__, t_begin))
        print('LOG: Running method "%s"' % func.__name__)
        func_params = get_func_params(func, *args, **kwargs)
        print(func.__name__ + "params dict:======>" + str(func_params))
        result = func(*args, **kwargs)
        print('LOG: Method "%s" completed' % func.__name__)
        print('LOG: Method "%s" result = %s' % (func.__name__, str(result)))
        t_end = time.time()
        print('%s method end at %0.4f' % (func.__name__, t_end))
        print('%s method executed in %s ms' % (func.__name__, t_end - t_begin))
        return result

    return wrapper


@with_method_logging
def sum(a, b, c):
    print(a + b + c)
    return a + b + c


class NovaApi():
    def __init__(self):
        self.ip = controller_ip
        self.port = nova_port
        self.http_protocol = http_protocol
        self.endpoint = '{}://{}:{}'.format(self.http_protocol, self.ip, self.port)
        self.token = Keystone.token
        self.admin_token = Keystone.admin_token
        self.DIR_PATH = os.path.dirname(__file__)
        self.log = Logger('../Log/Nova.log', level='info').logger

    def listVms(self):
        url = '{}/v2.1/servers'.format(self.endpoint)
        base_header["X-Auth-Token"] = self.token
        r = requests.get(url=url, headers=base_header, verify=False)
        if r.status_code == 200:
            res = json.loads(r.content)
            server_list = res.get('servers')
            return server_list
        else:
            self.log.error('list vms request failed! {}-{}'.format(r.status_code, r.content))
            return False

    @nova_new_header
    def addOneVmUseLocalDiskNet(self, name, imageRef, flavorRef, network_id,
                                availability_zone="nova", diskConfig="AUTO", description=None,
                                security_groups: list = [{"name": "default"}]):
        url = '{}/v2.1/servers'.format(self.endpoint)
        body = {
            "server": {
                "name": name,
                "imageRef": imageRef,
                "flavorRef": flavorRef,
                "availability_zone": availability_zone,
                "OS-DCF:diskConfig": diskConfig,
                "description": description,
                "security_groups": security_groups,
                "networks": [
                    {
                        "uuid": network_id,
                    }
                ]
            }
        }
        body = json.dumps(body)
        r = requests.post(url=url, data=body, headers=base_header, verify=False)
        if r.status_code == 202:
            res = json.loads(r.content)
            self.log.info('vm:{} create success!'.format(name))
            vm_info = res.get('server')
            return vm_info
        else:
            self.log.error('create vm failed!-{}-{}'.format(r.content, r.status_code))
            return False

# ————————————————
# 版权声明：本文为CSDN博主「Python测试和开发」的原创文章，遵循CC
# 4.0
# BY - SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https: // blog.csdn.net / qq_40442753 / article / details / 109734415
if __name__ == '__main__':
    sum(1, 2, 3)
class AuthClass:
    def __init__(self, name, pwd):
        self.name = name
        self.pwd = pwd

    def auth(self):
        if self.name == "python" and self.pwd == "123":
            return True
        else:
            return False


def auth_before(f):
    @wraps(f)
    def inner(*args, **kwargs):
        if not user.auth():
            print("用户名或密码错误")
            return False
        else:
            return f(*args, **kwargs)

    return inner


@auth_before
def p1():
    return "this is p1 function"


# Press the green button in the gutter to run the script.
if __name__ == '__main__':

    user = AuthClass("python", "123")
    # result = auth_before(p1)

    print(p1())

# # See PyCharm help at https://www.jetbrains.com/help/pycharm/
# ————————————————
# 版权声明：本文为CSDN博主「Take^that」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/qq_37767455/article/details/119674570